package hva.team2.viavia.tools;

/**
 * Created by sempere on 29/07/13.
 */

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;
import android.util.Log;

public class CItyDownloader extends Thread{

    //http://www.helloandroid.com/tutorials/how-download-fileimage-url-your-device

        private final String PATH = "/data/data/hva.team2.viavia/";  //put the downloaded file here\
        private String sourceUrl;
        private String fileName;

        public void setUrl(String sourceUrl){
             this.sourceUrl = sourceUrl;
        }

        public void setFileName(String fileName){
            this.fileName = fileName;
        }

        @Override
        public void run() {

            try {
                URL url = new URL(sourceUrl);
                //File file = new File(PATH + fileName);

                File file = new File (PATH + "sample.txt");
                long startTime = System.currentTimeMillis();

                URLConnection ucon = url.openConnection();

                InputStream is = ucon.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);

                ByteArrayBuffer baf = new ByteArrayBuffer(50);
                int current = 0;
                while ((current = bis.read()) != -1) {
                    baf.append((byte) current);
                }

                FileOutputStream fos = new FileOutputStream(file);
                fos.write(baf.toByteArray());
                fos.close();
                Log.d("ImageManager", "download ready in"
                        + ((System.currentTimeMillis() - startTime) / 1000)
                        + " sec");

            } catch (IOException e) {
                Log.d("ImageManager", "Error: " + e);
            }

        }
}
